using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Shop.Model;
using Shop.Framework.Services;
using System.Web.Script.Serialization;
using System.Text;
using System.IO;
using Shop.Framework.Runtime;

namespace Shop.Website.Controllers {
    public class CMSController : Controller {
        //
        // GET: /CMS/

        [CMSFilter]
        public ActionResult Index() {
            return View();
        }

        public ActionResult Login(string login, string password) {
            ShopService serv = new ShopService();
            serv.LogIn(login, password);
            return View("CategoryList");
        }
        #region Categories
        [CMSFilter]
        public ActionResult CategoryList() {
            return SelectCategory(0);
        }

        [CMSFilter]
        public ActionResult SaveCategory() {

            var cat = new Category {
                Name = Request.Form["name"],
                Description = Request.Form["description"],
                IdCategory = Convert.ToInt32(Request.Form["idCategory"]),
                Keywords = Request.Form["keywords"],
                Tags = Request.Form["tags"],
                Title = Request.Form["title"],
                IsDisabled = Convert.ToBoolean(Request.Form["isDisabled"])
            };

            CMS_CategoryService service = new CMS_CategoryService();
            if (cat.IdCategory == 0) {
                service.AddCategory(cat);
            } else {
                service.EditCategory(cat);
            }

            return View("CategoryList");
        }

        [CMSFilter]
        public ActionResult SelectCategory(int idCategory) {
            CategoryService service = new CategoryService();
            Category cat = service.GetCategoryById(idCategory);
            ViewData["CategoryInView"] = cat;
            return View();
        }

        [CMSFilter]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListAction() {
            if (!string.IsNullOrEmpty(Request.Form["Select"])) {
                CategoryService service = new CategoryService();
                int idCategory = Convert.ToInt32(Request.Form["idCategory"]);
                Category cat = service.GetCategoryById(idCategory);
                ViewData["CategoryInView"] = cat;
            } else {
                //TODO: Disable
            }

            return View("CategoryList");
        }
        #endregion

        #region Products

        [CMSFilter]
        public ActionResult ProductList(int idCategory, int page) {

            ProductService service = new ProductService();
            List<Product> productList = service.FindProducts(idCategory);

            //TODO: Encapsulate Vaue
            ViewData["TotalPage"] = productList.Count != 0 ? DeterminePageList(productList.Count) : 0;
            //TODO: Encapsulate Vaue
            ViewData["CurrentPage"] = page;
            ViewData["IdCategory"] = idCategory;
            ViewData["ProductList"] = productList;
            return View("ProductList");
        }

        [CMSFilter]
        private int DeterminePageList(int count) {

            int value = 0;

            if (count < 10 && count != 0)
                value = 1;
            else {
                value = count / 10;
                if (count % 10 != 0)
                    value += 1;
            }

            return value;
        }

        [CMSFilter]
        public ActionResult ProductDetail(int idCategory, int idProduct) {
            ProductService service = new ProductService();
            Product p = service.FindProduct(idProduct);
            ViewData["ProductDetail"] = p;
            ViewData["IdCategory"] = idCategory;

            return View("ProductDetail");
        }

        [CMSFilter]
        public ActionResult SaveProduct() {
            int idCategory = Convert.ToInt32(Request.Form["idCategory"]);
            Product p = new Product();
            p.IdProduct = Convert.ToInt32(Request.Form["idProduct"]);
            p.Name = Request.Form["name"];
            p.IdDesigner = Convert.ToInt32(Request.Form["idDesigner"]);
            p.Description = Request.Form["description"];
            p.Tags = Request.Form["tags"];
            p.Keywords = Request.Form["keywords"];
            p.IsDeleted = Convert.ToBoolean(Request.Form["isDeleted"]);
            p.IsViewable = Convert.ToBoolean(Request.Form["isViewable"]);
            p.Price = Convert.ToDecimal(Request.Form["price"]);
            p.TaxedPrice = Convert.ToDecimal(Request.Form["taxedPrice"]);
            p.Title = Request.Form["title"];
            p.DateEncoded = DateTime.Now;

            ProductService service = new ProductService();

            if (p.IdProduct != 0)
                service.SaveModified(p, idCategory);
            else
                service.SaveNewProduct(p, idCategory);

            //return ProductDetail(idCategory, p.IdProduct);
            return ProductList(idCategory, 1);
        }

        [CMSFilter]
        public ActionResult NewProduct(int idCategory) {

            ViewData["IdCategory"] = idCategory;
            Product p = new Product();
            p.Name = "New Product";
            ViewData["ProductDetail"] = p;
            return View("ProductDetail");
        }

        [CMSFilter]
        public ActionResult GetProductImageList(int idProduct) {

            ProductService service = new ProductService();

            ViewData["Product"] = service.FindProduct(idProduct);
            return View("ProductImage");
        }

        [CMSFilter]
        public ActionResult AddImage(int idProduct) {

            ProductService service = new ProductService();
            foreach (string upload in Request.Files) {
                string path = AppDomain.CurrentDomain.BaseDirectory + @"ProductImages\";
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                Request.Files[upload].SaveAs(Path.Combine(path, filename));
                service.AddImageToProduct(idProduct, filename);
            }


            return GetProductImageList(idProduct);
        }

        public ActionResult Logout() {
            CMSRuntime.Instance.Logout();
            return RedirectToAction("CategoryList");
        }

        [CMSFilter]
        public ActionResult ModifyImage(int idProduct, int idProductImage) {

            ProductService service = new ProductService();
            if (Request.Form["Delete"] != null) {
                service.DeleteImage(idProductImage, idProduct);
            } else {
                service.SetAsDefaultImage(idProduct, idProductImage);
            }

            return GetProductImageList(idProduct);
        }

        [CMSFilter]
        public ActionResult Orders() {
            string from = Request["dateFrom"];
            string to  = Request["dateTo"];
            if(from != null)
                from = Convert.ToDateTime(from).ToShortDateString() + " 12:00:00 PM";
            if(to != null)
                to = Convert.ToDateTime(to).ToShortDateString() + " 12:00:00 AM";

            ViewData["From"] = from;
            ViewData["To"] = to;
            
            return View();
        }

        [CMSFilter]
        public ActionResult Completed() {

            string id = Request["IdCustomer"];
            CustomerService service = new CustomerService();
            bool ok = service.SetCompleted(Convert.ToInt32(id));

            return RedirectToAction("Orders");
        }

        #endregion

        public ActionResult OrderDetail(int idCustomerOrder) {

            CustomerService service = new CustomerService();
            CustomerOrder order = service.GetCustomerOrders(idCustomerOrder);
            ViewData.Model = order;
            return View();
        }


    }
}
